import uuid
from rest_framework.views import APIView
from rest_framework.response import Response
from api.models import UserInfo,Token
from django.contrib import auth
import datetime

class LoginView(APIView):
    def post(self,request):
        res = {"user": None, "data": "", "msg": None}
        try:
            # 1.获取数据
            user = request.data.get("user")
            pwd = request.data.get('pwd')
            user_obj = auth.authenticate(username=user,password=pwd)

            if user_obj:
                random_str = str(uuid.uuid4()).replace('-','')
                # 如果没有key就创建，同时要更新创建的时间
                Token.objects.update_or_create(user=user_obj,defaults={"key":random_str,"created":datetime.datetime.now()})
                res["user"] = user_obj.username
                res["token"] = random_str
            else:
                res["msg"] = "用户名或者密码错误!"
        except Exception as e:
            res["msg"] = str(e)

        return Response(res)

